package com.jai.pms.message.listener;

import com.jai.pms.message.service.SceneService;
import com.jai.pms.message.service.ShotService;
import com.ruoyi.common.redis.service.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.stream.MapRecord;
import org.springframework.data.redis.connection.stream.RecordId;
import org.springframework.data.redis.stream.StreamListener;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Component
public class RedisStreamListener implements StreamListener<String, MapRecord<String, String, String>> {
    private static final Logger logger = LoggerFactory.getLogger(RedisStreamListener.class);

    @Autowired
    private RedisService redisService;

    @Autowired
    private ShotService shotService;

    @Autowired
    private SceneService sceneService;

    @Override
    public void onMessage(MapRecord<String, String, String> message) {
        String stream = message.getStream();
        RecordId recordId = message.getId();
//        User user = (User) message.getValue().get("user");
        logger.info("接收任务：{}, value = {}, thread = {}", recordId, message.getValue(), Thread.currentThread().getName());
//        String service = message.getValue().get("service");
//        if (service != null) {
//            try {
//                Class.forName(service);
//            } catch (ClassNotFoundException e) {
//                logger.error("service: {} 不存在", service);
//            }
//        }
        boolean isSuccess = false;
        String service = message.getValue().get("service").replaceAll("\"", "");
        String method = message.getValue().get("method").replaceAll("\"", "");
        String id = message.getValue().get("id");
        if (Objects.equals(service, "shot")) {
            isSuccess = shotService.onMessage(method, id);
        } else if (Objects.equals(service, "scene")) {
            isSuccess = sceneService.onMessage(method, id);
        }

        logger.info("处理完成：{}", recordId);
        if (isSuccess) {
            redisService.ackMessage(recordId);
        }
    }
}
